package com.lanou3g.code0418.control;

import java.util.concurrent.RecursiveTask;

/**
 * Created by dllo on 18/4/18.
 */
public class SumTask extends RecursiveTask<Long>{
//    private Long target;
//    private Long from;
//    //阈值 如果from和target的差> 该值,则 拆分任务
//    private static final long THRESHOLD = 50000000;
//
//    public SumTask(Long from, Long target) {
//        this.target = target;
//        this.from = from;
//    }
//

//    @Override
//    protected Long compute() {
//        if (target - from <= THRESHOLD) {
//            //任务已经足够小了
//            //自己计算完成 即可
//            Long sum = 0L;
//            for (long i = from; i <= target; i++) {
//                sum += i;
//            }
//            return sum;
//        }
//        //任务还是很大,需要拆分
//        //计算前一半的值
//        SumTask sumTask1 = new SumTask(from,(target+from)/2);
//        //计算后一半的值
//        SumTask sumTask2 = new SumTask((target+from)/2+1,target);
//
//        invokeAll(sumTask1,sumTask2);//关键代码
//
//        return sumTask1.join()+sumTask2.join();
//    }


    private Long target;
    private Long from;
    //阈值  如果from和target的差大于该值，则拆分任务
    private static final long THRESHOLD = 100000L;



    public SumTask(Long from,Long target) {

        this.target = target;
        this.from = from;
    }


    @Override
    protected Long compute() {
        if (target - from < THRESHOLD){
            //任务已经足够小了，自己计算完成即可
            long sum = 0L;
            for (long i = from; i <= target; i++){
                sum += i;
            }
            return sum;
        }
        // 任务还是很大，需要拆分

        //计算前一半的值
        SumTask sumTask1 = new SumTask(from,(target+from)/2);
        //计算后一半的值
        SumTask sumTask2 = new SumTask((target + from)/2+1,target);

        //开启执行，相当于 线程.start()
        invokeAll(sumTask1,sumTask2); //关键代码

//        sumTask1.fork();  //错误使用
//        sumTask2.fork();

        return  sumTask1.join() + sumTask2.join();

    }
}
